package com.zplh.zplh_android_yk.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.zplh.zplh_android_yk.TaskManager;
import com.zplh.zplh_android_yk.bean.MessageBean;
import com.zplh.zplh_android_yk.bean.TaskBean;
import com.zplh.zplh_android_yk.event.JpushEvent;
import com.zplh.zplh_android_yk.utils.MessageUtils;
import com.zplh.zplh_android_yk.utils.RxBus;

import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;
import zplh.com.commonlibrary.utils.GsonUtils;

/**
 * Created by yong hao zeng on 2018/7/5.
 */
public class MyJpushReceiver extends BroadcastReceiver {
    String tag = "极光推送";
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();

        //自定义消息处理
        if (intent.getAction().equals(JPushInterface.ACTION_MESSAGE_RECEIVED)){
            String data = bundle.getString(JPushInterface.EXTRA_EXTRA);
            if (TextUtils.isEmpty(data)) return;
//            LogUtils.d(tag,data);
            try {
                MessageBean messageBean = GsonUtils.changeGsonToBean(data, MessageBean.class);
                if (TextUtils.isEmpty(messageBean.getContent().getData().getEntrance())) {
                    return;
                }
                JSONObject object = new JSONObject(data);
                TaskBean taskBean = MessageUtils.message2Task(object.getJSONObject("content").get("data").toString());
                if (taskBean ==null||TextUtils.isEmpty(taskBean.getMethodName())) return;
                TaskManager.getInstance().addTask(taskBean);
            }catch (Exception e){

                return;
            }

        }else if (intent.getAction().equals(JPushInterface.ACTION_CONNECTION_CHANGE)){
            boolean connected = bundle.getBoolean(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            JpushEvent event = new JpushEvent();
            event.setType(1);
            event.setSatate(connected?"正常":"断开");
            RxBus.getInstance().post(event);

        }
    }
}
